// Helene Martin, CSE 143 // This program counts the number of words in a large file. // It demonstrates the use of a Set collection. import java.io.*; import java.util.*; // smallmoby mobydick // ArrayList 1477 3881 // HashSet 326 417 // TreeSet 345 452 public class WordCount { public static void main(String[] args) throws FileNotFoundException { // List words = new ArrayList(); Set words = new TreeSet(); System.out.println("Reading file..."); // Scanner input = new Scanner(new File("smallmoby.txt")); Scanner input = new Scanner(new File("mobydick.txt")); long start = System.currentTimeMillis(); while (input.hasNext()) { String word = input.next(); // if (!words.contains(word)) { // needed for ArrayList but not for // Sets words.add(word); // } } long end = System.currentTimeMillis(); long elapsed = end - start; System.out.println("The file has " + words.size() + " words."); System.out.println("Took " + elapsed + " ms."); // iterate over a set using a for-each loop // for (String word : words) { // System.out.println(word); // } } }